import React from 'react';
import { Popover } from 'antd';
import cn from 'classnames';

import styles from './index.less';

const isNotValid = value => Number.isNaN(value) || Math.abs(value) === Infinity;

const renderPopLine = (label, value) => (
    <div className={styles.popLine}>
        <div className={styles.popLabel}>{label}:</div>
        <div className={styles.popValue}>{isNotValid(value) ? '--' : value}</div>
    </div>
);

const renderChange = value => {
    const getColor = () => {
        if (isNotValid) return 'same';
        if (value > 0) {
            return 'up';
        }
        if (value < 0) {
            return 'down';
        }
        return 'same';
    };
    const formatNumber = isNotValid(value) ? '--' : value * 100;
    const percent = String(formatNumber).includes('.') ? formatNumber.toFixed(2) : formatNumber;
    return (
        <>
            <div className={cn(styles.changeArrow, styles[getColor()])} />
            <div className={cn(styles.changeNumber, styles[getColor()])}>{`${percent}%`}</div>
        </>
    );
};

const getShowTitle = (item, titleKey) => (titleKey ? item[titleKey] : item.title);

// 如果重叠
// const checkOverlay = (sourceData, baseWidth) => {
//     // 经验值
//     const threshold = 40;
//     const overlayResult = {};
//     if (!baseWidth || !sourceData.length) return overlayResult;

//     // 选择第一个作为基准
//     let level = 0;
//     overlayResult[sourceData[0].title] = level;

//     for (let i = 0; i < sourceData.length - 1; i += 1) {
//         for (let j = 0; j < sourceData.length - i - 1; j += 1) {
//             const prev = sourceData[j];
//             const next = sourceData[j + 1];
//             if (
//                 (Math.abs(prev.value - next.value) / 100) * baseWidth < threshold &&
//                 overlayResult[next.title] === undefined
//             ) {
//                 level += 1;
//                 overlayResult[next.title] = level;
//             }
//         }
//     }

//     return overlayResult;
// };

// title顺序有约束
// pop的内容有强业务约束
// 暂时不可任意配置
const renderPop = (target, salaryData, titleKey) => {
    const [origin, suggest, expect] = salaryData;

    const baseContent = ( // popover前两行
        <>
            {renderPopLine(target.title, target.numWithCurrencyUnit)}
            {renderPopLine(target.subTitle, target.subNumWithCurrencyUnit)}
        </>
    );
    if (target === suggest) {
        return (
            <>
                {baseContent}
                {renderPopLine(
                    `对比${getShowTitle(origin, titleKey)}`,
                    renderChange((target.num - origin.num) / origin.num)
                )}
                {renderPopLine(
                    `对比${getShowTitle(expect, titleKey)}`,
                    renderChange((target.num - expect.num) / expect.num)
                )}
            </>
        );
    }
    if (target === expect) {
        return (
            <>
                {baseContent}
                {renderPopLine(
                    `对比${getShowTitle(origin, titleKey)}`,
                    renderChange((target.num - origin.num) / origin.num)
                )}
                {renderPopLine(
                    `对比${getShowTitle(suggest, titleKey)}`,
                    renderChange((target.num - suggest.num) / suggest.num)
                )}
            </>
        );
    }
    return baseContent;
};

const formatPercent = value => parseInt(value, 10);

const TAG_OFFSET = 13; // 调整Y轴高度，线长稍小于真实百分比

export default function ScaleBar({ sourceData = [], titleKey }) {
    const baseRef = React.useRef();
    const baseNumAry = [25, 50, 75];

    // const overlayMap = checkOverlay(sourceData, baseRef.current?.offsetWidth);

    // console.log(overlayMap);

    const getPosition = (index, length) => ((index + 1) * 100) / (length + 1);

    return (
        <div className={styles.wrap}>
            <div className={styles.base} ref={baseRef}>
                <div className={cn(styles.arrow, styles.baseEnd)} />
                <div className={styles.baseNum} style={{ bottom: 0 }}>
                    0
                </div>
                {baseNumAry.map((item, index) => (
                    <div
                        key={item}
                        className={styles.baseNum}
                        style={{ bottom: `${getPosition(index, baseNumAry.length)}%` }}
                    >
                        {formatPercent(item)}
                    </div>
                ))}
                {sourceData.map((item, index) => (
                    <div
                        key={item.title}
                        className={styles.sourceWrap}
                        style={{ left: `${getPosition(index, sourceData.length)}%` }}
                    >
                        <div
                            className={styles.baseTitle}
                            style={{
                                color: item.scaleColor || item.color
                            }}
                        >
                            {getShowTitle(item, titleKey)}
                        </div>
                        <Popover
                            overlayClassName={styles.popOverlay}
                            content={renderPop(item, sourceData, titleKey)}
                            title={item.title}
                        >
                            <div
                                className={styles.tagsLine}
                                style={{
                                    background: item.color,
                                    color: item.color,
                                    height: `calc(${item.value}% - ${TAG_OFFSET}px)`
                                }}
                            >
                                <div
                                    className={styles.tags}
                                    style={{
                                        background: item.color,
                                        color: item.fontColor
                                    }}
                                >
                                    {item.value ? formatPercent(item.value) : ''}分位
                                </div>
                            </div>
                        </Popover>
                    </div>
                ))}
            </div>
        </div>
    );
}
